package com.wnxy.portal.interceptor;

import cn.hutool.jwt.JWTUtil;
import com.wnxy.portal.common.constant.RedisConstant;
import com.wnxy.portal.common.util.IpUtil;
import com.wnxy.portal.common.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenUtil tokenUtil;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 访问资源之前，需要校验请求头是否包含token、token合法性
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("请求地址：{}",request.getRequestURL());
        // 获取token
        String token = request.getHeader("Authorization");
        if (!StringUtils.hasText(token)) {
            log.error("拦截器校验失败，Token为空");
            response.sendRedirect("/login.html");
            return false;
        }
        // token格式： Authorization "Bearer xx"
        token = token.replace("Bearer ", "");

        // 校验token
        if (!tokenUtil.verify(token)) {
            log.error("校验失败，token不合法");
            response.sendRedirect("/login.html");
            return false;
        }

        // 解析token，获取用户id
        String userId = (String) JWTUtil.parseToken(token).getPayload("userId");
        String ip = (String) JWTUtil.parseToken(token).getPayload("ip");

        // token安全： 1、登录时候token中记录ip； 2、校验：当前ip必须要与tokenip一致；否则token泄露
        String nowIp = IpUtil.getIpAddr(request);
        log.debug("拦截器校验，token中的ip：{}; 当前ip：{}",ip,nowIp);
        if (!nowIp.equals(ip)) {
            log.error("校验失败，token可能已经泄露");
            response.sendRedirect("/login.html");
            return false;
        }

        // 校验是否过期: 获取redis中token
        String key = RedisConstant.USER_TOKEN_PREFIX + userId;
        if (!redisTemplate.hasKey(key)) {
            log.error("校验失败，token已过期");
            response.sendRedirect("/login.html");
            return false;
        }

        // token 续期
        redisTemplate.expire(key,300, TimeUnit.MINUTES);

        // 校验成功，放行
        return true;
    }
}
